﻿using UnityEngine;
using System.Collections;
namespace GX
{
	public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
	{
		private static T _instance;

		public static T Instance
		{
			get
			{
					if (_instance == null)
					{
						_instance = (T)FindObjectOfType(typeof(T));

						if (_instance == null)
						{
							GameObject singleton = new GameObject("(singleton) " + typeof(T));
							_instance = singleton.AddComponent<T>();
							DontDestroyOnLoad(singleton);

							Debug.Log(string.Format("[Singleton] An instance of {0} is needed in the scene, so '{1}' was created with DontDestroyOnLoad.", typeof(T), singleton));
						}
						else
						{
							Debug.Log(string.Format("[Singleton] Using instance already created: {0}", _instance.gameObject.name));
						}
					}
					return _instance;
			}
		}
	}
}
